package com.ruoyi.system.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MeetUser;
import com.ruoyi.system.service.IMeetUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 会议人员管理Controller
 *
 * @author ruoyi
 * @date 2025-01-06
 */
@RestController
@RequestMapping("/system/meetUser")
public class MeetUserController extends BaseController
{
    @Autowired
    private IMeetUserService meetUserService;

    /**
     * 查询会议人员管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(MeetUser meetUser)
    {
        startPage();
        List<MeetUser> list = meetUserService.selectMeetUserList(meetUser);
        return getDataTable(list);
    }

    /**
     * 导出会议人员管理列表
     */
    @Log(title = "会议人员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MeetUser meetUser)
    {
        List<MeetUser> list = meetUserService.selectMeetUserList(meetUser);
        ExcelUtil<MeetUser> util = new ExcelUtil<MeetUser>(MeetUser.class);
        util.exportExcel(response, list, "会议人员管理数据");
    }

    /**
     * 获取会议人员管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(meetUserService.selectMeetUserById(id));
    }

    /**
     * 新增会议人员管理
     */
    @Log(title = "会议人员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MeetUser meetUser)
    {
        // 设置默认参会状态为未参会
        if (meetUser.getIsAttented() == null) {
            meetUser.setIsAttented("1");
        }
        return toAjax(meetUserService.insertMeetUser(meetUser));
    }

    /**
     * 修改会议人员管理
     */
    @Log(title = "会议人员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MeetUser meetUser)
    {
        return toAjax(meetUserService.updateMeetUser(meetUser));
    }

    /**
     * 删除会议人员管理
     */
    @Log(title = "会议人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(meetUserService.deleteMeetUserByIds(ids));
    }

    /**
     * 修改会议人员状态和签到时间
     */
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody MeetUser meetUser)
    {
        if (meetUser.getId() == null || meetUser.getMeetId() == null) {
            return error("参数错误");
        }

        try {
            // 只更新状态和签到时间
            MeetUser updateUser = new MeetUser();
            updateUser.setId(meetUser.getId());
            updateUser.setMeetId(meetUser.getMeetId());
            updateUser.setIsAttented(meetUser.getIsAttented());  // 已经是String类型
            updateUser.setFtime(meetUser.getFtime());

            return toAjax(meetUserService.updateMeetUserStatus(updateUser));
        } catch (Exception e) {
            return error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 添加会议参与者
     */
    @PostMapping("/addParticipant")
    public AjaxResult addParticipant(@RequestParam Long meetId, @RequestParam Long userId)
    {
        try {
            // 检查是否已经存在该参会记录
            if (meetUserService.existByMeetIdAndUserId(meetId, userId)) {
                return error("该用户已经参加了该会议");
            }

            // 创建新的会议参与者记录
            MeetUser meetUser = new MeetUser();
            meetUser.setMeetId(meetId);
            meetUser.setUserId(userId);
            meetUser.setIsAttented("1"); // 默认未参会状态
            
            return toAjax(meetUserService.insertMeetUser(meetUser));
        } catch (Exception e) {
            return error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 查询会议参会人员详情
     */
    @GetMapping("/listByMeetId/{meetId}")
    public AjaxResult listByMeetId(@PathVariable("meetId") Long meetId)
    {
        try {
            if (meetId == null) {
                return error("会议ID不能为空");
            }
            
            MeetUser queryParam = new MeetUser();
            queryParam.setMeetId(meetId);
            List<MeetUser> list = meetUserService.selectMeetUserList(queryParam);
            
            // 获取第一条记录的会议信息
            String theme = list.isEmpty() ? "" : list.get(0).getTheme();
            String meetContent = list.isEmpty() ? "" : list.get(0).getMeetContent();
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("theme", theme);
            result.put("meetContent", meetContent);
            result.put("participants", list.stream().map(user -> {
                Map<String, Object> participant = new HashMap<>();
                participant.put("Id", user.getId());
                participant.put("userName", user.getUserName());
                participant.put("isAttented", user.getIsAttented());
                participant.put("ftime", user.getFtime());
                participant.put("avatar", user.getAvatar());  // 添加头像信息
                return participant;
            }).collect(Collectors.toList()));
            
            return success(result);
        } catch (Exception e) {
            return error("查询失败：" + e.getMessage());
        }
    }
}
